package com.treeroot.treenet.entity;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * Create By TreeRoot
 * Create Time: 2023/12/18 03:39
 * Class Name: Response
 * Description:
 * 基础相应体
 *
 * @author TreeRoot
 */

@Data
public class Response {
    private String version;
    private int code;
    private String status;
    private Map<String, String> headers;
    private String message;


    /**
     * 生成响应
     *
     * @param request  请求
     * @param response 响应
     * @return 2023/11/07
     */

    public static String buildResponse(Request request, String response) {
        Response httpResponse = new Response();
        httpResponse.setCode(200);
        httpResponse.setStatus("ok");
        httpResponse.setVersion(request.getVersion());

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Content-Length", String.valueOf(response.getBytes().length));
        httpResponse.setHeaders(headers);
        httpResponse.setMessage(response);
        StringBuilder builder = new StringBuilder();
        buildResponseLine(httpResponse, builder);
        buildResponseHeaders(httpResponse, builder);
        buildResponseMessage(httpResponse, builder);
        return builder.toString();
    }


    /**
     * 建立响应行
     *
     * @param response      响应
     * @param stringBuilder 字符串生成器
     * @return 字符串生成器
     * 2023/11/07
     */

    private static StringBuilder buildResponseLine(Response response, StringBuilder stringBuilder) {
        return stringBuilder
                .append(response.getVersion())
                .append(" ")
                .append(response.getCode())
                .append(" ")
                .append(response.getStatus())
                .append("\n");
    }

    /**
     * 生成响应标头
     *
     * @param response      回答
     * @param stringBuilder 字符串生成器
     * @return 字符串生成器
     * 2023/11/07
     */

    private static StringBuilder buildResponseHeaders(Response response, StringBuilder stringBuilder) {
        for (Map.Entry<String, String> entry : response.getHeaders().entrySet()) {
            stringBuilder.append(entry.getKey()).append(":").append(entry.getValue()).append("\n");
        }
        return stringBuilder.append("\n");
    }

    /**
     * 生成响应消息
     *
     * @param response      回答
     * @param stringBuilder 字符串生成器
     * @return 字符串生成器
     * 2023/11/07
     */

    private static StringBuilder buildResponseMessage(Response response, StringBuilder stringBuilder) {
        return stringBuilder.append(response.getMessage());
    }
}